<?php

namespace control;
/*
*采购收货单类
*/

class purchaseGetOrderClass extends adIndexClass
{
    private const page = 'purchaseGetOrder';
    private const table = 'purchase_get_order';
    private const tableMx = 'purchase_get_order_detail';
    private const title = '采购收货单';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'supplierPurchaseGetSearch':
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'num' => [
                        'name'  => "数量",
                        'width' => 200,
                    ],
                    'money'  => [
                        'name'  => '金额(' . static::$unit . ')',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'recordDate'         => [
                        'name'  => '单据日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ]
                ];
                break;
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'supplier' => [
                        'name'  => "供应商",
                        'width' => 260,
                    ],
                    'tag'  => [
                        'name'  => "单据标签",
                        'width' => 260,
                    ],
                    'num'         => [
                        'name'  => '数量',
                        'width' => 200,
                    ],
                    'money'          => [
                        'name'  => '金额(' . static::$unit . ')',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function supplierPurchaseGetOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")).
                        hidden(array("name" => "targetId", "value" => $this->get('id'))),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 供应商页卡
     * @return bool|string
     */
    public function supplierPurchaseGet(): bool|string
    {
        $html = $this->supplierPurchaseGetOptions(false);
        $button = "";
        if ($this->power(self::page, "print")) {
            $button .= sprintf("<span onclick=\"batchPrint('%s', {targetId: '%s'})\" class='spanButton'>打印设置</span>\n", $this->get('cla'), $this->get('id'));
        }
        //返回
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function supplierPurchaseGetSearch(): bool|string
    {
        $targetId = $this->post('targetId');
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),
            'coid'  => self::$coid
        );
        $and = " and supplierId = '$targetId'";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //生成查询语句
        $where = search([
                "="    => $equal,
                "like" => $like,
            ]) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => ["title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=detail&id=' . $array['id'] . "')"],
            );

            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "num":
                        $num = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]'", 'sum' => "num"));
                        $row[] = $num;
                        break;
                    case "money":
                        $row[] = self::lostZero($array['money']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='invoiceForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "标签"   => text(array("name" => "tages")),
                    '供应商' => supplierClass::supplierSelect(array('title' => '')),
                ],
                [
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isEdit = $this->power(self::page, "edit");
        if ($isEdit) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($isEdit) {
            $button .= "<span onclick=\"layer('orderTag','batchAddTags',{'table':'".self::table."','title':'".self::title."'})\" class='spanButton'>批量打标签</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>批量打印</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }


    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "state"      => $this->post('state'),
            "supplierId" => $this->post('supplierId'),
            'coid'       => self::$coid
        );
        $and = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        if ($this->post('tages')) {
            $and .= " and (";
            $tagsArr = explode('，', $this->post('tages'));
            foreach ($tagsArr as $index => $tag) {
                $and .= $index == 0 ? "tags like '%" . $tag . "%'" : " and tags like '%" . $tag . "%'";
            }
            $and .= ")";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isEdit = $this->power(self::page, "edit");
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box"    => array("name" => "listId", "value" => $array['id']),
                "edit"   => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                'print'  => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
                'track'  => array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=采购收货单&id=" . $array['id'] . "')"),
            );
            if ($array['state'] != '草稿' || !$isEdit) {
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "supplier":
                        $supplier = query('supplier', "id = '$array[supplierId]'");
                        $row[] = $supplier['name'];
                        break;
                    case "tag":
                        $tag = orderTagClass::getTagName($array['id']);
                        $row[] = $tag;
                        break;
                    case "num":
                        $num = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]'", 'sum' => "num"));
                        $row[] = $num;
                        break;
                    case "money":
                        $row[] = self::lostZero($array['money']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalNum = find([
            'table'  => self::tableMx,
            'single' => "orderId in (select id from ".self::table." where 1=1 {$where})",
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $totalMoney = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'num'        => self::lostZero($totalNum['num'], 'numPrecision'),
            'money'      => self::lostZero($totalMoney['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        $button[] = [
            "name"  => "保存为草稿",
            "type"  => "点击事件",
            "title" => "保存",
            'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
        ];
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        $result = find(array('table' => 'warehouse', 'field' => 'id,name', 'where' => "coid = '" . self::$coid . "' and state = '启用' order by time desc"));
        $tr[] = [
            '',
            '物料编码',
            '物料名称',
            '规格型号',
            '单位',
            "<div class='warehouse'><span class='word'>仓库</span>&emsp;" . self::chooseSelect($result['array'], 'warehouseId[]', 'warehouse') . "</div>",
            '提货重量（吨）',
            '批次',
            '单价(' . static::$unit . ')',
            '未税金额（' . static::$unit . '）',
            '<div class="rate">' . '税率%' . saleOrderClass::chooseRate() . '</div>',
            '税额（' . static::$unit . '）',
            '价税合计（' . static::$unit . '）',
            '关联采购订单',
            '备注'
        ];
        $totalArr = ['total_num'=>0,'total_row_money'=>0,'total_tax_money'=>0,'total_money'=>0];
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        foreach ($result['array'] as $k=>$array) {
            $material = query('material', " id = '$array[materialId]'");
            $money = self::formattingFigure($array['money'] - $array['taxMoney']);
            $purchaseOrderMx = query("purchase_order_detail", "id = '$array[sourceId]'");
            $purchaseOrder = query('purchase_order', "id = '$purchaseOrderMx[orderId]'");
            $batch = text(array('name' => 'batch[]', 'title' => '请填写', 'value' => $array['batch']));
            $tr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])) .
                hidden(array('name' => 'sourceId[]', 'value' => $array['sourceId'])),
                $material['code'],
                $material['name'],
                $material['model'],
                select(array('name' => 'unitDetail[]', 'data' => ['unit' => $array['unit']], 'change' => 'unitChange', 'option' => machiningOrderClass::unitOption($material['id']), 'title' => '单位', 'value' => $array['unit'])),
                idSelect(array('name' => 'warehouseId[]', 'sqlForm' => "warehouse where coid = '" . self::$coid . "' and state = '启用' order by time desc", 'sqlId' => 'id', 'sqlField' => "name", 'title' => '仓库', 'value' => $array['warehouseId'])),
                text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countMoney', 'value' => self::lostZero($array['num'], 'numPrecision'))),
                "<span class='batch'>{$batch}</span>",
                text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'blur' => 'countMoney', 'value' => self::lostZero($array['price'], 'pricePrecision'))),
                "<span class='rowMoney'>{$money}</span>",
                select(array('name' => 'rate[]', 'change' => 'countMoney', 'title' => '税率', 'option' => explode('，', para('taxRate')), 'value' => $array['rate'] * 100)),
                "<span class='taxMoney'>{$array['taxMoney']}</span>",
                text(array('name' => 'moneyWithTax[]', 'other' => self::digitalFiltering(), 'blur' => 'calculatePrice', 'value' => self::lostZero($array['money']))),
                $purchaseOrder['orderNo'],
                text(array('name' => 'mxText[]', 'value' => $array['text'])),
            ];
            $totalArr['total_num'] += $array['num'];
            $totalArr['total_row_money'] += $money;
            $totalArr['total_tax_money'] += $array['taxMoney'];
            $totalArr['total_money'] += $array['money'];
        }
        $checked = $info['isTax'] ? 'checked' : '';
        $total = [
            6 => "<span id='total_num'>".self::lostZero($totalArr['total_num'],'numPrecision')."</span>",
            9 => "<span id='total_row_money'>".self::lostZero($totalArr['total_row_money'])."</span>",
            11 => "<span id='total_tax_money'>".self::lostZero($totalArr['total_tax_money'])."</span>",
            12 => "<span id='total_money'>".self::lostZero($totalArr['total_money'])."</span>",
        ];
        $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));

        $chooseBtn = <<<eof
<span class="smallButton" onclick="layer('{$this->get('cla')}','addMx',$('form[name=purchaseGetOrderEditForm]').serialize())">选择产品</span>
eof;
        //选项控制
        $setting = optionSettingClass::getSetting('采购');
        if (isset($setting['purchaseMustOrder']) && $setting['purchaseMustOrder']) {
            $chooseBtn = '';
        }
        $mxButton = <<<efo
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addOrder',$('form[name=purchaseGetOrderEditForm]').serialize())">关联采购单</span>
                $chooseBtn
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addSupplierPrice',$('form[name=purchaseGetOrderEditForm]').serialize())">选择供应商物料</span>
                <span style="margin-left: 20px;">
                    <label class='checkbox'><input name='isTax' onclick="taxChange(this)" type='checkbox' $checked value='1'><span></span>&nbsp;含税</label>
                </span>
efo;

        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "供应商："   => supplierClass::supplierSelect(array('value' => $info['supplierId'], 'param' => "{type:'启用'}")),
                    //selectMultiple(["name" => "supplierId", "value" => $info['supplierId'], 'where' => "coid = '" . self::$coid . "' and state = '启用'", 'table' => "supplier", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '请选择']),
                    must . "单据日期：" => text(["name" => "recordDate", 'class' => 'text', 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    "采购暂估："     => radio(array('name' => 'estimation', 'value' => ['1' => '是', '0' => '否'], 'checked' => $info['estimation'] ?: '0')),
                    "实际交货日期：" => text(["name" => "actual_delivery_date", 'class' => 'text', 'laydate' => [], "value" => $info['actual_delivery_date'] ?: $this->date]),
                ],
                [
                    "结算方式：" => radio(array('name' => 'settlementType', 'change' => 'settlementDayDefault', 'checked' => $info['settlementType'], 'value' => array_merge(para('supplierSettlement', '，'), ['月结']))) . "&nbsp;" . text(array('name' => 'settlementDay', 'type' => 'number', 'value' => $info['settlementDay'], 'title' => '结算周期')),
                ],
                [
                    "备注："     => textarea(["name" => "text", 'class' => 'text', "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '收货明细',
            'button' => $mxButton,
            'html' => $list,
        ]);
        $body .= $this->editBlock([
            '附件' => fileUploadClass::addFileComponent($id, '采购收货单', self::page, self::page . 'EditForm')
        ]);
        $data['html'] = $this->pageEdit([
            "html"  => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $saleOrderObj = new saleOrderClass();
        $data['html'] .= <<<efo
<script>
function addRow(classify=''){
     if (classify === 'addMx'){
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
             $("#materialTable tbody").append(res.html);
             resetNumber($("#materialTable"))
             calculateTotal()
         },'json');
     }else if(classify === 'supplierPrice'){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addSupplierPriceEdit',$("form[name='supplierPriceForm']").serialize(),function(res) {
            $("#materialTable tbody").append(res.html);
            resetNumber($("#materialTable"))
            calculateTotal()
        },'json');
     }else{
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addOrderEdit',$("form[name='saleOrderForm']").serialize(),function(res) {
             $("#materialTable tbody").append(res.html);
             resetNumber($("#materialTable"))
             calculateTotal()
             if (res.isTax){
                $("[name='isTax']").prop('checked', true)
                 taxChange();
             }
         },'json');
     }
}
</script>

efo. $saleOrderObj->editJs();;
        //返回
        return $this->tab($data);
    }


    /**
     * 已在采购收货单中的数量
     */
    private function purchaseGetNum($purchaseGetOrderId, $sourceId, $toUnit): float
    {
        $num = 0;
        $all = find(array('table' => 'purchase_get_order_detail', "where" => "sourceId = '$sourceId' and orderId !='$purchaseGetOrderId'  and coid = '" . self::$coid . "'"));
        foreach ($all['array'] as $array) {
            $num += machiningOrderClass::material_num_change($array['materialId'], $array['unit'], $toUnit, $array['num']);
        }
        $all = find(array('table' => 'purchase_refund_order_detail as a join purchase_refund_order as b on a.orderId = b.id', 'field' => "a.*", "where" => "a.sourceId = '$sourceId'  and a.coid = '" . self::$coid . "' and b.state = '已确认'"));
        foreach ($all['array'] as $array) {
            $num -= machiningOrderClass::material_num_change($array['materialId'], $array['unit'], $toUnit, $array['num']);
        }
        return self::formattingFigure($num, 'numPrecision');
    }

    public function editEdit()
    {
        $fileIdArr = $this->post('fileId');
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId') ?: [];
        $materialIdArr = $this->post('materialId');
        $sourceIdArr = $this->post('sourceId');
        $unitArr = $this->post('unitDetail');
        $numArr = $this->post('num');
        $batchArr = $this->post('batch');
        $priceArr = $this->post('price');
        $warehouseIdArr = $this->post('warehouseId');
        $taxRateArr = $this->post('rate');
        $moneyWithTaxArr = $this->post('moneyWithTax');
        $mxTextArr = $this->post('mxText');
        $field = [
            'text'                 => $this->post('text'),
            'supplierId'           => $this->post('supplierId'),
            'recordDate'           => $this->post('recordDate'),
            'isTax'                => $this->post('isTax') ? 1 : 0,
            'settlementType'       => $this->post('settlementType'),
            'settlementDay'        => $this->post('settlementDay'),
            'estimation'           => $this->post('estimation'),
            'actual_delivery_date' => $this->post('actual_delivery_date'),
        ];
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (!empty($info['id']) && $info['state'] != '草稿') {
            $json['warn'] = '此采购单非草稿状态，不能修改';
        } else {
            $warn = '';
            if(is_array($mxIdArr) && count($mxIdArr) > 0) {
                //选项控制
                $setting         = optionSettingClass::getSetting('采购');
                $dataIntegration = self::dataArrangement($sourceIdArr, $numArr);
                //判断收货数量是否超过总数量加上浮值
                foreach ($mxIdArr as $k => $mxId) {
                    if (isset($sourceIdArr[$k]) && !empty($sourceIdArr[$k])) {
                        //此采购单物料总数量
                        $purchaseOrderMx = query('purchase_order_detail', "id = '$sourceIdArr[$k]'");
                        //已存在的收货数量
                        $num         = $this->purchaseGetNum($id, $sourceIdArr[$k], $purchaseOrderMx['unit']);
                        $material    = query('material', "id = '$purchaseOrderMx[materialId]'");
                        if (isset($setting['purchaseStrict']) && $setting['purchaseStrict']) {
                            $material['upBuy'] = 0;
                        }
                        $getNum = machiningOrderClass::material_num_change($purchaseOrderMx['materialId'], $unitArr[$k], $purchaseOrderMx['unit'], $dataIntegration[$sourceIdArr[$k]]);
                        if (self::formattingFigure($num + $getNum, 'numPrecision') > $purchaseOrderMx['num'] * (1 + $material['upBuy'])) {
                            $warn = "物料【{$material['name']}】的数量已超出订单总数量";
                            break;
                        }
                    }

                }
            }
            if (!empty($warn)) {
                $json['warn'] = $warn;
            } else {
                $this->startTrans();
                $isPass = true;//事务通过标志
                if (!$info['id']) {
                    $userNo = codeTemplateClass::generateCode(self::page, [
                        'prefix' => 'CGSH' . date('Ymd', strtotime($field['recordDate'])),
                        'table'  => self::table,
                        'field'  => 'orderNo',
                        'where'  => '',
                    ], $field);
                    $field = array_merge($field, [
                        'id'      => $id,
                        'orderNo' => $userNo,
                        'state'   => '草稿',
                        'coid'    => self::$coid,
                        'stid'    => $this->control['stid'],
                    ]);
                    $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
                } else {
                    $json['warn'] = static::update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => $where
                    ]);
                }
                //添加或更新明细
                if (is_array($mxIdArr)) {
                    foreach ($mxIdArr as $k => $nid) {
                        $mx = query(self::tableMx, "id = '$nid'");
                        $numArr[$k] = self::formattingFigure($numArr[$k], 'numPrecision');
                        $priceArr[$k] = self::formattingFigure($priceArr[$k], 'pricePrecision');
                        //数据格式处理
                        $taxRateArr[$k] = floatval($taxRateArr[$k]) / 100;//税率从百分比转为小数
                        $result = saleOrderClass::isTax($numArr[$k], $priceArr[$k], $taxRateArr[$k], $field['isTax']);
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::tableMx,
                                "field" => [
                                    'sourceId'        => $sourceIdArr[$k],
                                    'materialId'      => $materialIdArr[$k],
                                    'unit'            => $unitArr[$k],
                                    'num'             => $numArr[$k],
                                    'batch'           => $batchArr[$k],
                                    'price'           => $priceArr[$k],
                                    'taxMoney'        => $result['taxMoney'],//税额
                                    'moneyWithOutTax' => $result['money'],//不含税金额
                                    'money'           => self::formattingFigure($moneyWithTaxArr[$k]),//价税合计
                                    'rate'            => $taxRateArr[$k],
                                    'warehouseId'     => $warehouseIdArr[$k],
                                    'text'     => $mxTextArr[$k],
                                ],
                                "where" => " id = '$nid'"
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::tableMx,
                                "field" => [
                                    'id'              => $nid,
                                    'orderId'         => $id,
                                    'coid'            => self::$coid,
                                    'sourceId'        => $sourceIdArr[$k],
                                    'materialId'      => $materialIdArr[$k],
                                    'unit'            => $unitArr[$k],
                                    'num'             => $numArr[$k],
                                    'batch'           => $batchArr[$k],
                                    'price'           => $priceArr[$k],
                                    'taxMoney'        => $result['taxMoney'],//税额
                                    'moneyWithOutTax' => $result['money'],//不含税金额
                                    'money'           => self::formattingFigure($moneyWithTaxArr[$k]),//价税合计
                                    'rate'            => $taxRateArr[$k],
                                    'warehouseId'     => $warehouseIdArr[$k],
                                    'text'     => $mxTextArr[$k],
                                ],

                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $isPass = false;
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    $warn = update(array(
                        'table' => 'file',
                        'field' => ['targetId' => $id],
                        'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"
                    ));
                    if ($warn != '更新成功') {
                        $json['warn'] = $warn;
                        $isPass = false;
                    }
                }
                if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                    $this->commitTrans();
                    delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                    $money = find(array('table' => self::tableMx, 'single' => "orderId = '$id'", 'field' => "ifnull(sum(money),0) as total"))['total'];
                    update(array('table' => self::table, 'field' => ['money' => self::formattingFigure($money)], 'where' => "id = '$id'"));
                    if ($json['warn'] == '新增成功') {
                        self::insertOperateLog($id,self::title,"新建");
                    }
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn'] = 2;
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                } else {
                    $this->rollback();
                }
            }

        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 关联采购单
     * @return bool|string
     */
    public function addOrder(): bool|string
    {
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $html =
            text(array("name" => "orderNo", "title" => "采购订单号")) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "单据日期")) .
            text(array("name" => "createTime", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "交货日期")) .
            text(array("name" => "code", "title" => "产品编码")) .
            text(array("name" => "materialName", "title" => "产品名称")) .
            text(array("name" => "model", "title" => "规格型号")) .
            hidden(array('name' => 'id', 'value' => $this->post('id'))) .
            hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
            hidden(array('name' => 'supplierId', 'value' => $this->post('supplierId'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
        $button = "<input onclick=\"addRow();$('#" . $layerId . "').remove()\" type='button' class='searchSub m-l-5' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 关联采购单
     * @return bool|string
     */
    public function addOrderSearch(): bool|string
    {
        $supplierId = $this->post('supplierId');
        //$sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];//  and mx.id not in ('" . implode("','", $sourceId) . "')";
        $where = " po.coid='" . self::$coid . "'  and  po.supplierId = '$supplierId' ";
        $and = " and po.isClose = 0 ";
        // 是否按订单严格采购
        if(optionSettingClass::getSettingItem('采购','purchaseStrict')){
            $and .= " and mx.num > mx.receive_num ";
        }
        $like = [
            'po.orderNo' => $this->post('orderNo'),
            'mat.code'   => $this->post('code'),
            'mat.name'   => $this->post('materialName'),
            'mat.model'  => $this->post('model'),
        ];
        $equal = [
            'po.type'  => '购货',
            'po.state' => '已确认',
        ];
        if ($this->post('createTime')) {
            //交货日期
            $and .= self::timeComparison($this->post('createTime'), 'date', 'po.deliveryDate');
        }
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), 'date', 'po.recordDate');
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table"   => "purchase_order_detail as mx join purchase_order as po on mx.orderId = po.id join material as mat on mx.materialId = mat.id ",
            "field"   => "mx.id,mx.num,mx.receive_num,po.orderNo,po.deliveryDate,po.recordDate,mat.code,mat.name,mat.model",
            "where"   => $where,
            'pageNum' => 50,
            "order"   => "po.recordDate desc,po.`time` desc",
        ]);
        $tip = componentClass::promptSvg('采购订单可选范围：1、状态为已确认，2、选项设置为严格按订单采购则待采购数量需大于零');
        //获取表头
        $checkAll = $this->checkAll("saleOrderForm", "purchaseOrderDetailId");
        $tr[] = [$checkAll, '采购订单号', '单据日期', '交货日期', '物料编码', '物料名称', '规格型号', '应采购数量', '已采购数量', '待采购数量'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "purchaseOrderDetailId", "value" => $array['id']),
            );
            $tr[] = array(
                $this->dominate($dominate),
                $array['orderNo'],
                $array['recordDate'],
                $array['deliveryDate'],
                $array['code'],
                $array['name'],
                $array['model'],
                self::lostZero($array['num'], 'numPrecision'),
                self::lostZero($array['receive_num'], 'numPrecision'),
                self::lostZero($array['num'] - $array['receive_num'], 'numPrecision'),
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='saleOrderForm'>" .
            hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
            hidden(array('name' => 'id', 'value' => $this->post('id'))) .
            $this->tableMany(array("tr" => $tr, "showSort" => true, "sortTitle" => $tip, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 关联采购单
     */
    public function addOrderEdit()
    {
        $id = $this->post('id');
        $isTax = $this->post('isTax');
        $mxIdArr = $this->post('purchaseOrderDetailId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择销售单';
        } else {
            $tr = [];
            $isOrderTax = 0;
            foreach ($mxIdArr as $purchaseOrderDetailId) {
                $purchaseOrderMx = find(array(
                    'table' => "purchase_order as a join purchase_order_detail as b on a.id = b.orderId",
                    'single' => " b.id = '$purchaseOrderDetailId' order by list asc",
                    'field' => "b.*,a.orderNo,a.isTax"
                ));
                if (!$isOrderTax && $purchaseOrderMx['isTax']) {
                    $isOrderTax = $purchaseOrderMx['isTax'];
                }
                $material = query('material', "id = '$purchaseOrderMx[materialId]'");
                $select = select(array(
                    'name' => 'rate[]',
                    'change' => 'countMoney',
                    'value' => $purchaseOrderMx['rate'] * 100,
                    'title' => '税率',
                    'option' => explode('，', para('taxRate'))
                ));
                $unitSelect = select(array(
                    'name' => 'unitDetail[]',
                    'data' => ['unit' => $purchaseOrderMx['unit']],
                    'change' => 'unitChange',
                    'option' => machiningOrderClass::unitOption($material['id']),
                    'title' => '单位',
                    'value' => $purchaseOrderMx['unit']
                ));
                $warehouse = idSelect(array(
                    'name' => 'warehouseId[]',
                    'sqlForm' => "warehouse where coid = '" . self::$coid . "' and state = '启用' order by time desc",
                    'sqlId' => 'id',
                    'sqlField' => "name",
                    'title' => '仓库'
                ));
                //除开当前订单的剩余可收货数量
                $num = $this->purchaseGetNum($id, $purchaseOrderMx['id'], $purchaseOrderMx['unit']);
                $num = ($purchaseOrderMx['num'] - $num) > 0 ? self::formattingFigure($purchaseOrderMx['num'] - $num, 'numPrecision') : 0;
                $purchaseOrderMx['price'] = self::formattingFigure($purchaseOrderMx['price'], 'pricePrecision');
                $moneyRes = saleOrderClass::isTax($num, $purchaseOrderMx['price'], $purchaseOrderMx['rate'], $isTax);
                $money = $moneyRes['money'];
                $taxMoney = $moneyRes['taxMoney'];
                $moneyWithTax = $moneyRes['moneyWithTax'];
                $uid = self::getId();
                $batch = text(array('name' => 'batch[]', 'title' => '请填写', 'value' => ''));
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $uid)) .
                    hidden(array('name' => 'materialId[]', 'value' => $purchaseOrderMx['materialId'])) .
                    hidden(array('name' => 'sourceId[]', 'value' => $purchaseOrderMx['id'])),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $unitSelect,
                    $warehouse,
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countMoney', 'value' => $num)),
                    "<span class='batch'>{$batch}</span>",
                    text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'blur' => 'countMoney', 'value' => $purchaseOrderMx['price'])),
                    "<span class='rowMoney'>{$money}</span>",
                    $select,
                    "<span class='taxMoney'>{$taxMoney}</span>",
                    text(array('name' => 'moneyWithTax[]', 'other' => self::digitalFiltering(), 'blur' => 'calculatePrice', 'value' => $moneyWithTax)),
                    $purchaseOrderMx['orderNo'],
                    text(array('name' => 'mxText[]', 'value' => ''))
                ];
            }
            $json['warn'] = 2;
            $json['isTax'] = $isOrderTax;
            $json['html'] = $this->tableMany(array("tr" => $tr,"thead" => false));
        }
        return json_encode($json, 320);
    }

    /**
     * 关联供应商物料
     * @return bool|string
     */
    public function addSupplierPrice(): bool|string
    {
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'supplierPriceForm';
        $html =
            materialClass::typeSelect(name: 'type') .
            text(array("name" => "code", "title" => "物料编码")) .
            text(array("name" => "materialName", "title" => "物料名称")) .
            text(array("name" => "model", "title" => "规格型号")) .
            hidden(array('name' => 'id', 'value' => $this->post('id'))) .
            hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
            hidden(array('name' => 'supplierId', 'value' => $this->post('supplierId'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
        $button = "<input onclick=\"addRow('supplierPrice');removeSelectedContent('" . $formName . "')\" type='button' class='searchSub m-l-5' value='继续添加'>";
        $button .= "<input onclick=\"addRow('supplierPrice');$('#" . $layerId . "').remove()\" type='button' class='searchSub m-l-5' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 关联供应商物料
     * @return bool|string
     */
    public function addSupplierPriceSearch(): bool|string
    {
        //$sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];//" and ssp.id not in ('" . implode("','", $sourceId) . "')";
        $where = " ssp.coid='" . self::$coid . "' ";
        $like = [
            'mat.code'  => $this->post('code'),
            'mat.name'  => $this->post('materialName'),
            'mat.model' => $this->post('model'),
            'mat.typePath' => $this->post('type'),
        ];
        $equal = [
            'ssp.supplierId' => $this->post('supplierId'),
        ];
        $where .= search(["like" => $like, "=" => $equal]);
        $page = $this->page([
            "table"   => " store_supplier_price as ssp join material as mat on ssp.materialId = mat.id ",
            "field"   => "ssp.id,mat.typeId,mat.typeName,mat.code,mat.name,mat.model",
            "where"   => $where,
            'pageNum' => 50,
            "order"   => "ssp.`time` desc",
        ]);
        $materialObj = new materialClass();
        //获取表头
        $checkAll = $this->checkAll("supplierPriceForm", "supplierPriceId");
        $tr[] = [$checkAll, '分类', '物料编码', '物料名称', '规格型号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "supplierPriceId", "value" => $array['id']),
            );
            $tr[] = array(
                $this->dominate($dominate),
                $array['typeName'],
                $array['code'],
                $array['name'],
                $array['model'],
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='supplierPriceForm'>" .
            hidden(array('name' => 'isTax', 'value' => $this->post('isTax'))) .
            hidden(array('name' => 'id', 'value' => $this->post('id'))) .
            $this->tableMany(array("tr" => $tr)) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 关联供应商价格表
     */
    public function addSupplierPriceEdit()
    {
        $id = $this->post('id');//采购订单ID
        $isTax = $this->post('isTax');
        $mxIdArr = $this->post('supplierPriceId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择供应商物料';
        } else {
            $tr = [];
            foreach ($mxIdArr as $supplierPriceId) {
                $store_supplier_price = query('store_supplier_price', "id = '$supplierPriceId'");
                $material = query('material', "id = '$store_supplier_price[materialId]'");
                $id = self::getId();
                $batch = text(array('name' => 'batch[]', 'title' => '请填写', 'value' => ''));;
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $id)) .
                    hidden(array('name' => 'materialId[]', 'value' => $store_supplier_price['materialId'])) .
                    hidden(array('name' => 'sourceId[]', 'value' => '')),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    select(array('name' => 'unitDetail[]', 'data' => ['unit' => $material['unit']], 'change' => 'unitChange', 'option' => machiningOrderClass::unitOption($material['id']), 'title' => '单位', 'value' => $material['unit'])),
                    idSelect(array('name' => 'warehouseId[]', 'sqlForm' => "warehouse where coid = '" . self::$coid . "' and state = '启用' order by time desc", 'sqlId' => 'id', 'sqlField' => "name", 'title' => '仓库')),
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countMoney')),
                    "<span class='batch'>{$batch}</span>",
                    text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'blur' => 'countMoney')),
                    "<span class='rowMoney'>0</span>",
                    select(array('name' => 'rate[]', 'change' => 'countMoney', 'title' => '税率', 'option' => explode('，', para('taxRate')))),
                    "<span class='taxMoney'>0</span>",
                    text(array('name' => 'moneyWithTax[]', 'other' => self::digitalFiltering(), 'blur' => 'calculatePrice')),
                    '-',
                    text(array('name' => 'mxText[]', 'value' => ''))
                ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
        }
        return json_encode($json, 320);
    }

    /**
     *
     * @return bool|string
     */
    public function addMx()
    {
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = '';
        $data             = [
            'sub'            => " onclick=\"addRow('addMx');$('#" . $layerId . "').remove()\" ",
            'continueAdding' => $notAllowRepeat ? " onclick=\"addRow('addMx');removeSelectedContent('" . $formName . "')\" " : " onclick=\"addRow('addMx');\" ",
            'hidden'         => hidden(["name" => "notAllowRepeat", "value" => $notAllowRepeat]) .
                hidden(["name" => "supplyControl", "value" => '允许采购']) .
                hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '')),
        ];
        return $materialClassObj->addMx($data);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择产品';
        } else {
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $material = query('material', "id = '$mxId'");
                $id = self::getId();
                $batch = text(array('name' => 'batch[]', 'title' => '请填写', 'value' => ''));;
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $id)) .
                    hidden(array('name' => 'materialId[]', 'value' => $mxId)) .
                    hidden(array('name' => 'sourceId[]', 'value' => '')),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    select(array('name' => 'unitDetail[]', 'data' => ['unit' => $material['unit']], 'change' => 'unitChange', 'option' => machiningOrderClass::unitOption($material['id']), 'title' => '单位', 'value' => $material['unit'])),
                    idSelect(array('name' => 'warehouseId[]', 'sqlForm' => "warehouse where coid = '" . self::$coid . "' and state = '启用' order by time desc", 'sqlId' => 'id', 'sqlField' => "name", 'title' => '仓库')),
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countMoney')),
                    "<span class='batch'>{$batch}</span>",
                    text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'blur' => 'countMoney')),
                    "<span class='rowMoney'>0</span>",
                    select(array('name' => 'rate[]', 'change' => 'countMoney', 'title' => '税率', 'option' => explode('，', para('taxRate')))),
                    "<span class='taxMoney'>0</span>",
                    text(array('name' => 'moneyWithTax[]', 'other' => self::digitalFiltering(), 'blur' => 'calculatePrice')),
                    '-',
                    text(array('name' => 'mxText[]', 'value' => ''))
                ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
        }
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name"  => "复核",
                    "type"  => "弹出层",
                    "cla"   => $this->get('cla'),
                    "fun"   => "operate",
                    "post"  => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($info['state'] == '草稿') {
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name"  => "提交",
                        "type"  => "弹出层",
                        "cla"   => $this->get('cla'),
                        "fun"   => "operate",
                        "post"  => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                    //按钮
                    $button[] = [
                        "name"  => "编辑",
                        "type"  => "顶部页卡",
                        "title" => "编辑用户",
                        "url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    ];
                }
                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla"  => $this->get('cla'),
                        "fun"  => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }
            //按钮
            $button[] = [
                "name" => "打印",
                "type" => "点击事件",
                "fun"  => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
            ];

            if ($this->power(self::page, "confirm") && $info['state'] != '草稿') {
                //按钮
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            $button[] = [
                "name"  => "单据追踪",
                "type"  => "顶部页卡",
                "title" => "单据追踪",
                "url"   => $this->root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=采购收货单&id=" . $info['id'],
            ];
            //操作记录
            $button[] = self::operateLogBut($info['id'],1);

            $isTax = $info['isTax'] ? '含税' : '不含税';
            $tr[] = ['物料编码', '物料名称', '规格型号', '单位', '仓库', '提货数量（吨）', '批次', $isTax . '单价(' . static::$unit . ')', '未税金额（' . static::$unit . '）', '税率%', '税额（' . static::$unit . '）', '价税合计（' . static::$unit . '）', '关联采购订单', '备注'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $material = query('material', " id = '$array[materialId]'");
                $purchaseOrderMx = query("purchase_order_detail", "id = '$array[sourceId]'");
                $purchaseOrder = query('purchase_order', "id = '$purchaseOrderMx[orderId]'");
                $tr[] = [
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    warehouseClass::getName($array['warehouseId']),
                    self::lostZero($array['num'], 'numPrecision'),
                    $array['batch'],
                    self::lostZero($array['price'], 'pricePrecision'),
                    self::formattingFigure($array['money'] - $array['taxMoney']),
                    ($array['rate'] * 100) . '%',
                    self::lostZero($array['taxMoney']),
                    self::lostZero($array['money']),
                    $purchaseOrder['orderNo'],
                    $array['text'],
                ];
            }
            $total = find(array(
                'table' => self::tableMx,
                'field' => "
                ifnull(sum(num),0) as num,
                ifnull(sum(money),0) as totalMoney,
                ifnull(sum(taxMoney),0) as taxMoney,
                ifnull(sum(money-taxMoney),0) as money
                ",
                'single' => "orderId = '$info[id]'"));
            $total['num'] = $total['num'] ? self::lostZero($total['num'], 'numPrecision') : 0;
            $total['totalMoney'] = $total['totalMoney'] ? self::lostZero($total['totalMoney']) : 0;
            $total['taxMoney'] = $total['taxMoney'] ? self::lostZero($total['taxMoney']) : 0;
            $total['money'] = $total['money'] ? self::lostZero($total['money']) : 0;
            $total_tr = [
                5=>$total['num'],
                8=>$total['money'],
                10=>$total['taxMoney'],
                11=>$total['totalMoney'],
            ];
            $supplier = query('supplier', "id = '$info[supplierId]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '详细信息' => array(
                    array(
                        "供应商"   => $supplier['name'],
                        "单据日期" => self::null($info['recordDate']),
                        '采购暂估' => $info['estimation'] ? '是' : '否',
                        "结算方式" => $info['settlementType'] . ($info['settlementType'] == '月结' ? '-' . $info['settlementDay'] . '天' : ''),
                    ),
                    array(
                        "实际交货日期" => $info['actual_delivery_date'],
                        "单据编号" => $info['orderNo'],
                        "制单人"   => self::findStaff($info['stid']),
                        "状态"     => $info['state']
                    ),
                    array(
                        '单据标签' => orderTagClass::getTagName($info['id'])
                    ),
                    array(
                        "备注"     => pre($info['text']),
                    ),
                )
            ));
            $data['html'] .= $this->detailList([
                'title' => '收货明细',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailBlock([
                '附件' => fileUploadClass::showFile($info['id'], '采购收货单')
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 确认
     */
    public function confirmEdit(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state'       => '已确认',
            'checkId'     => self::$stid,
            'confirmTime' => $this->time
        ];

        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购收货单';
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此报价单不是待确认状态，不能确认';
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            //生成入库单
            $bool = $this->insertInventory($info);
            if ($bool !== true) {
                $json['warn'] = $bool;
            }
            //更新订单实际交货日期
            $this->updateDeliveryDate($info);
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])) {
                    self::insertOperateLog($info['id'],self::title,"提交、复核");
                }else{
                    self::insertOperateLog($info['id'],self::title,"复核");
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 更新订单实际交货日期
     */
    private function updateDeliveryDate($info): bool|string
    {
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
        $get_order_id = [];
        foreach ($result['array'] as $array) {
            if (!empty($array['sourceId'])) {
                $purchase_order_detail = query('purchase_order_detail', "id = '$array[sourceId]'", "id,orderId,num,receive_num,sourceId");
                $getTotal         = find(array(
                    'table'  => self::tableMx,
                    'single' => " sourceId = '$purchase_order_detail[id]' and orderId in (select id from purchase_get_order where coid = '" . self::$coid . "' and state = '已确认') ",
                    'field'  => "ifnull(sum(num),0) as num"
                ));
                // 增加采购订单的已收货数量
                update(array(
                    "table" => 'purchase_order_detail',
                    "field" => ['receive_num' => $getTotal['num']],
                    "where" => "id = '$purchase_order_detail[id]'",
                ));
                if (!in_array($purchase_order_detail['orderId'], $get_order_id)) $get_order_id[] = $purchase_order_detail['orderId'];

                // 增加采购申请的收货数量
                if (!empty($purchase_order_detail['sourceId'])) {
                    $purchase_apply_detail = query('purchase_apply_detail', "id = '$purchase_order_detail[sourceId]'", "id,receive_num");
                    if (!empty($purchase_apply_detail['id'])) {
                        $getTotal         = find(array(
                            'table'  => 'purchase_order_detail',
                            'single' => " sourceId = '$purchase_apply_detail[id]' and orderId in (select id from purchase_order where coid = '" . self::$coid . "' and state = '已确认') ",
                            'field'  => "ifnull(sum(num),0) as purchase_num,ifnull(sum(receive_num),0) as receive_num"
                        ));
                        update(array(
                            "table" => 'purchase_apply_detail',
                            "field" => ['purchase_num' => (float)$getTotal['purchase_num'], 'receive_num' => (float)$getTotal['receive_num']],
                            "where" => "id = '$purchase_apply_detail[id]'",
                        ));
                    }
                }
            }
        }
        //修改主订单
        foreach ((array)$get_order_id as $orderId) {
            $purchase_order = query('purchase_order', "id = '$orderId'", "id,actual_delivery_date,deliveryDate");
            $field = [];
            // 实际交货日期
            if (empty($purchase_order['actual_delivery_date'])) {
                $field['actual_delivery_date'] = $info['actual_delivery_date'];
                $field['deliver_on_schedule'] = (strtotime($info['actual_delivery_date'])<=strtotime($purchase_order['deliveryDate']))?1:2;
            }else{
                // 没有收货
                if(static::total(array('table' => 'purchase_order_detail', 'where' => " orderId = '" . $orderId . "' and coid = '" . self::$coid . "' and receive_num > 0 ")) == 0){
                    $field['actual_delivery_date'] = null;
                    $field['deliver_on_schedule'] = 0;
                }
            }
            // 自动关闭采购订单
            $purchaseClose = optionSettingClass::getSettingItem('采购', 'purchaseClose');
            if ($purchaseClose) {
                if (static::total(array('table' => 'purchase_order_detail', 'where' => " orderId = '" . $orderId . "' and coid = '" . self::$coid . "' and receive_num < num ")) == 0){
                    $field['isClose'] = 1;
                }else{
                    $field['isClose'] = 0;
                }
            }
            if (!empty($field)) {
                update(array(
                    "table" => 'purchase_order',
                    "field" => $field,
                    "where" => "id = '$purchase_order[id]'",
                ));
            }

        }
        return true;
    }

    /**
     * 生成入库单
     */
    private function insertInventory($info): bool|string
    {
        $confirmTime = $info['actual_delivery_date']?:$this->time;
        $auto = false;
        if (optionSettingClass::getSettingItem('采购', 'purchaseAutoIn')) {
            $auto = true;
        }
        $quality = [];//质检分组
        $re_array = [];//根据仓库重新分组
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
        foreach ($result['array'] as $array) {
            $material = query('material', "id = '$array[materialId]'");
            if ($material['IQC']) {
                //质检
                $quality[$array['materialId']][$array['id']] = ['num' => $array['num']];
            }
            $re_array[$array['warehouseId']][] = $array['id'];
        }
        // 有来料质检，并且入库前需要先完成质检，则不会自动入库
        if(!empty($quality) && optionSettingClass::getSettingItem('库存', 'inStockQuality')){
            $auto = false;
        }
        $inventory_to_quality = [];//把库存ID插入质检单中
        $supplier = query('supplier', "id = '$info[supplierId]'");
        $index = 1;
        foreach ($re_array as $warehouseId => $array) {

            $id = self::getId();
            $field = [
                'id'               => $id,
                'type'             => '采购收货',
                'coid'             => self::$coid,
                'sourceTable'      => self::table,
                'sourceId'         => $info['id'],
                'warehouseId'      => $warehouseId,
                'targetId'         => $info['supplierId'],
                'classify'         => 1,
                'state'            => $auto ? '已入库' : '待入库',
                'workFlow'         => (!empty($quality) ? '待质检' : '已质检'),
                'stid'             => self::$stid,
                'orderDate'        => $this->date,
                'sourceDate'       => $info['recordDate'],
                'sourceNo'         => $info['orderNo'],
                'sourceTargetName' => $supplier['name'],
                'text'             => $auto ? '自动入库' : '',
                'commitTime'       => $auto ? $confirmTime : '',
                'confirmTime'      => $auto ? $confirmTime : '',
            ];
            $userNo = codeTemplateClass::generateCode('inStock', [
                'prefix' => 'KCRK' . date('Ymd'),
                'table'  => 'inventory',
                'field'  => 'orderNo',
                'where'  => " and coid = '" . self::$coid . "'",
                'index'  => $index
            ], $field);
            $field['orderNo'] = $userNo;
            $warn = static::insert(array(
                'table' => 'inventory',
                'field' => $field
            ));
            if ($warn != '新增成功') {
                return "新增入库单失败";
            }
            //自动入库则生成入库变动记录
            if ($auto) {
                $changeId = self::getId();
                $fieldChange = [
                    'id'               => $changeId,
                    'coid'             => self::$coid,
                    'type'             => '采购收货',
                    'classify'         => 1,
                    'targetId'         => $info['supplierId'],
                    'sourceTargetName' => $supplier['name'],
                    'confirmTime'      => $confirmTime,
                    'reviewTime'       => $confirmTime,
                    'state'            => '已复核',
                    'stid'             => self::$stid,
                ];
                $userNo = codeTemplateClass::generateCode('inStock', [
                    'prefix' => 'RKD' . date('Ymd'),
                    'table'  => 'inventory_changes',
                    'field'  => 'orderNo',
                    'where'  => " and coid = '" . self::$coid . "'",
                    'index'  => $index,
                ], $fieldChange);
                $fieldChange['orderNo'] = $userNo;
                $warn = static::insert(array(
                    'table' => 'inventory_changes',
                    'field' => $fieldChange
                ));
                if ($warn != '新增成功') {
                    return "新增入库变动失败";
                }
            }
            $index++;
            foreach ($array as $mxId) {
                $mx = query(self::tableMx, "id = '$mxId'");
                $inventory_to_quality[$mxId] = $id;
                $inventoryMxId = self::getId();
                $warn = static::insert(array(
                    'table' => 'inventory_detail',
                    'field' => [
                        'id'            => $inventoryMxId,
                        'coid'          => self::$coid,
                        'sourceTable'   => self::tableMx,
                        'sourceId'      => $mx['id'],
                        'materialId'    => $mx['materialId'],
                        'warehouseId'   => $warehouseId,
                        'unit'          => $mx['unit'],
                        'orderId'       => $id,
                        'orderNum'      => $mx['num'],
                        'batch'         => $mx['batch'],
                        'num'           => $auto ? $mx['num'] : 0,
                        'rate'          => $info['isTax'] ? 0 : $mx['rate'],
                        'price'         => $mx['price'],
                        'money'         => $auto ? $mx['money'] : 0,
                        'quality'       => isset($quality[$mx['materialId']][$mxId]) ? 1 : 0,
                        'pass_num'      => isset($quality[$mx['materialId']][$mxId]) ? 0 : $mx['num'],
                    ]
                ));
                if ($warn != '新增成功') {
                    return "新增入库单明细失败";
                }

                if ($auto) {
                    //生成出库变动记录
                    $warn = static::insert(array(
                        'table' => 'inventory_changes_detail',
                        'field' => $fieldChangeMx = [
                            'id'            => self::getId(),
                            'coid'          => self::$coid,
                            'orderId'       => $changeId,
                            'materialId'    => $mx['materialId'],
                            'orderNum'      => $mx['num'],
                            'batch'         => $mx['batch'],
                            'num'           => $mx['num'],
                            'unit'          => $mx['unit'],
                            'price'         => $mx['price'],
                            'money'         => self::formattingFigure($mx['price'] * $mx['num']),
                            'sourceTable'   => 'inventory_detail',
                            'sourceId'      => $inventoryMxId,
                            'sourceNo'      => $field['orderNo'],
                            'warehouseId'   => $warehouseId,
                        ]
                    ));
                    if ($warn != '新增成功') {
                        return "新增出库变动明细失败";
                    }
                    //生成应收应付
                    $res = $field;
                    $targetDate = $targetNo = $targetText = $hiddenText = ' ';
                    if ($res['sourceTable']) {
                        $obj = query($res['sourceTable'], " id = '{$res['sourceId']}' ");
                        if (!empty($obj['id'])) {
                            $targetDate = $obj['recordDate'];
                            $targetNo = $obj['orderNo'];
                            $targetText = $res['type'] . "单【{$obj['orderNo']}】";
                            $hiddenText = $res['type'] . '单ID：' . $obj['id'] . '，入库单ID：' . $id . '入库单子ID：' . $inventoryMxId;
                        }
                    }
                    $bool = supplierClass::insertRecord($res['targetId'], '采购收货', $mx['money'], self::tableMx, $info['id'], $targetDate, $targetNo, $targetText, $hiddenText, $fieldChangeMx['id']);
                    if ($bool !== true) {
                        return '生成应付记录失败';
                    }
                    $mainUnitNum = inventoryBalanceClass::toMainUnit($mx['materialId'], $mx['num'], $mx['unit']);
                    $bool = inventoryBalanceClass::inventoryControl($mx['materialId'], $mainUnitNum, "top");  //最高库存控制
                    if ($bool !== true) {
                        return $bool;
                    }
                    $material = query("material", " id = '" . $mx['materialId'] . "' ");
                    $material['positionId'] = inventoryBalanceClass::matchLocation($warehouseId);
                    $batch = $mx['batch'] ? $mx['batch'] : ($material['isBatch'] == 1 ? inStockClass::getBatchNo($res['type'], $res['targetId']) : '');  //物料需要管理批号则生成批号
                    //单位单价转换
                    $price = round($mx['num'] * (float)$mx['price'] / (float)$mainUnitNum, 4);
                    inventoryDefaultClass::recordInventoryPrice($mx['materialId'], $mainUnitNum, $price);//计算记录加权平均单价
                    $recordId = self::getNo();
                    insert([
                        'table' => 'inventory_record',
                        'field' => [
                            'id'            => $recordId,
                            'coid'          => self::$coid,
                            'warehouseId'   => $warehouseId,
                            'positionId'    => $material['positionId'],
                            'materialId'    => $mx['materialId'],
                            'inventoryId'   => $id,
                            'inventoryMxId' => $inventoryMxId,
                            'batch'         => $batch,
                            'num'           => $mainUnitNum,
                            'changesId'     => $fieldChangeMx['id'],
                            'defaultPrice'     => $price,
                            'time'     => $confirmTime,
                        ],
                    ]);
                    if (!empty($material['positionId'])) inventoryBalanceClass::recordStockToLocation($recordId, ['positionId' => $material['positionId']]);
                    auditingFollow([
                        "type"   => "入库单",
                        "typeId" => self::generateId([$id, $mx['materialId']]),
                        "text"   => "【{$this->control['name']}】通过自动入库【{$mx['num']}】",
                    ]);
                }
            }
        }

        //质检
        $index = 1;
        foreach ($quality as $materialId => $array) {
            foreach ($array as $mxId => $val) {
                $mx = query(self::tableMx, "id = '$mxId'");
                $material = query('material', "id = '$materialId'");
                $allTypeId = explode('/',$material['typePath']);
                //查找质检方案
                $quarantine = query(
                    'quarantine',
                    "application like '%来料检验%' and coid = '" . self::$coid . "' and state = '启用' and startDate<= date_format(now(),'%Y-%m-%d') and endDate>date_format(now(),'%Y-%m-%d')  and if(materialId!='',materialId = '$material[id]',materialTypeId in ('" . implode("','", $allTypeId) . "')) order by materialId desc,list desc,time desc"
                );

                if (empty($quarantine['id'])) {
                    return "未找到物料【{$material['name']}】的质检方案";
                }
                //根据质检批量分成几组
                $num = $quarantine['qualityBatch'] > 0 ? ceil($val['num'] / $quarantine['qualityBatch']) : 1;
                $userNo = codeTemplateClass::generateCode('materialInspection', [
                    'prefix' => 'IN' . date('Ymd'),
                    'table'  => 'quality_order',
                    'field'  => 'orderNo',
                    'where'  => " and coid = '" . self::$coid . "'",
                    'index'  => $index
                ], []);
                $index++;
                if ($num > 100) {
                    return "质检批量过小，新增质检单数量超过100条";
                }
                for ($i = 1; $i <= $num; $i++) {
                    $id = self::getId();
                    $remindNum = ($val['num'] - ($i - 1) * $quarantine['qualityBatch']);
                    $warn = static::insert(array(
                        'table' => 'quality_order',
                        'field' => [
                            'id'            => $id,
                            'type'          => 1,
                            'warehouseId'   => $mx['warehouseId'],
                            'inventoryId'   => $inventory_to_quality[$mx['id']] ?? '',
                            'coid'          => self::$coid,
                            'sourceTable'   => self::table,
                            'sourceId'      => $info['id'],
                            'sourceMxId'=>$mx['id'],
                            'targetId'      => $info['supplierId'],
                            'num'           => $remindNum > $quarantine['qualityBatch'] && $quarantine['qualityBatch'] > 0 ? $quarantine['qualityBatch'] : $remindNum,
                            'materialId'    => $material['id'],
                            'unit'          => $mx['unit'],
                            'orderNo'       => $userNo,
                            'batch'         => $userNo . '-' . $i,
                            'qid'           => $quarantine['id'],
                            'sourceNo'      => $info['orderNo'],
                            'state'         => '待质检',
                        ]
                    ));
                    if ($warn != '新增成功') {
                        return "新增质检单失败";
                    }
                    $all = find(array('table' => 'quarantine_item', 'where' => "orderId = '$quarantine[id]' order by list"));
                    foreach ($all['array'] as $item) {
                        $warn = static::insert(array(
                            'table' => 'quality_order_item',
                            'field' => [
                                'id'      => self::getId(),
                                'coid'    => self::$coid,
                                'orderId' => $id,
                                'itemId'  => $item['id'],
                            ]
                        ));
                        if ($warn != '新增成功') {
                            return "新增质检单明细质检项目失败";
                        }
                    }
                }
            }
        }
        return true;
    }


    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state'       => '草稿',
            'checkId'     => '',
            'confirmTime' => ''
        ];

        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购收货单';
        } elseif ($info['state'] == '草稿') {
            $json['warn'] = '此发货单是草稿状态，无需撤回';
        } elseif (static::total(array('table' => 'inventory', "where" => "sourceId = '$info[id]' and coid = '" . self::$coid . "' and state in ('部分入库','已入库')")) > 0) {
            $json['warn'] = '此收货单已存在有入库的单据，不能撤回';
        } elseif (static::total(array('table' => 'quality_order', "where" => "sourceId = '$info[id]' and coid = '" . self::$coid . "' and state ='已质检'")) > 0) {
            $json['warn'] = '此收货单已存在有已质检的单据，不能撤回';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //删除入库单
                delete(array('table' => 'inventory_detail', 'where' => "orderId in (select id from inventory where sourceId = '$info[id]' and coid = '" . self::$coid . "')"));
                delete(array('table' => 'inventory', 'where' => "sourceId = '$info[id]'"));
                //删除质检单
                delete(array('table' => 'quality_order_item', 'where' => "orderId in (select id from quality_order where sourceId = '$info[id]' and coid = '" . self::$coid . "')"));
                delete(array('table' => 'quality_order_reason', 'where' => "orderId in (select id from quality_order where sourceId = '$info[id]' and coid = '" . self::$coid . "')"));
                delete(array('table' => 'quality_order', 'where' => "sourceId = '$info[id]'"));
                //更新订单实际交货日期
                $this->updateDeliveryDate($info);
                self::insertOperateLog($info['id'],self::title,"撤回");
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '撤回成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }
    /**
     * Desc : 提交前数据验证
     * User : you name
     * Date : 2023-11-17 16:04
     * @param $info
     * @return string|bool
     */
    public function dataValidation($info): string|bool
    {
        $annotation = [
            'supplierId' => '供应商',
            'recordDate' => '单据日期',
        ];
        $rules = [
            'supplierId' => 'required',
            'recordDate' => 'required|date',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($info, $rules)->isOk();
        if ($result === false) {
            return $vt->getErrs()[0];  // 多个规则提示最前面一条
        }
        $result = find(array('table' => self::tableMx, 'field' => 'id,materialId,num,unit,price,warehouseId', 'where' => "orderId = '$info[id]' order by list"));
        if(count($result['array']) == 0){
            return "请完善收货明细";
        }
        if(static::is_null_array(array_column($result['array'],'materialId'))){
            return "收货明细中物料不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'unit'))){
            return "收货明细中【单位】不能为空";
        }
//        if(static::is_null_array(array_column($result['array'],'warehouseId'))){
//            return "收货明细中【收货仓库】不能为空";
//        }
        if(static::is_null_array(array_column($result['array'],'price'))){
            return "收货明细中【单价】不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'num'),false)){
            return "收货明细中【数量】不能为空，且必须大于0";
        }

        return true;
    }

    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        //提交前数据验证
        $json['warn'] = $this->dataValidation($info);
        if($json['warn'] !== true){
            goto resp;
        }
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购收货单';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此采购收货单不是草稿状态，不能提交';
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));

            $all = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time asc"));
            foreach ($all['array'] as $array) {
                $material = query('material', "id = '$array[materialId]'");
                if ($material['IQC']) {
                    $allTypeId = explode('/',$material['typePath']);
                    //查找质检方案
                    $quarantine = query(
                        'quarantine',
                        "application like '%来料检验%' and coid = '" . self::$coid . "' and state = '启用' and startDate<= date_format(now(),'%Y-%m-%d') and endDate>date_format(now(),'%Y-%m-%d')  and if(materialId,materialId = '$material[id]',materialTypeId in ('" . implode("','", $allTypeId) . "')) order by materialId desc,list desc,time desc"
                    );
                    if (empty($quarantine['id'])) {
                        $json['warn'] = "未找到物料【{$material['name']}】的质检方案";
                        break;
                    }
                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])){
                    $resultJson = $this->confirmEdit();
                    $json = json_decode($resultJson,true);
                    if ($json['warn'] != 2){
                        $this->rollback();
                        goto resp;
                    }
                }else {
                    self::insertOperateLog($info['id'],self::title,"提交");
                }
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此采购收货单，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此采购收货单？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此采购收货单？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    fileClass::deleteFile($id);
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 批量打印
     *
     * @return string
     */
    public function batchPrint(): string
    {
        $lists = $this->get('lists');
        if (empty($lists)) {
            exit('参数错误');
        } else {
            $listId = base64_decode($lists, true);
            $array = explode(',', $listId);
            $data = [];
            foreach ($array as $id) {
                $data[] = static::printPage($id, false);
            }
            return (new printTemplateClass())->start(self::page, $data);
        }
    }

    /**
     * 打印
     *
     * @return string
     */
    public function printPage($param = '', $isReturn = true): string|array
    {
        $id = $param ?: $this->get('id');
        $info = query(self::table, " id = '$id'");
        $info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称//公司名称
        $info['title'] = self::title;
        $info['printTime'] = $this->time;
        $info['stid'] = self::findStaff($info['stid']);
        $info['checkId'] = '';
        $info['supplierName'] = query('supplier', "id = '$info[supplierId]'")['name'];
        $info['qr'] = "source=" . self::table . "&id=" . $info['id'];
        $info['tags'] = orderTagClass::getTagName($info['id']);
        $detail = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
        $items = [];
        $x = 1;
        $totalNum = 0;
        $totalMoney = 0;
        foreach ($detail as $array) {
            $material = query('material', "id = '$array[materialId]'");
            $items[] = [
                'no'              => $x,
                'materialCode'    => $material['code'],
                'materialName'    => $material['name'],
                'price'           => $array['price'],
                'rate'            => ($array['rate'] * 100) . '%',
                'taxMoney'        => $array['taxMoney'],
                'moneyWithOutTax' => round($array['money'] - $array['taxMoney'], 2),
                'money'           => $array['money'],
                'model'           => $material['model'],
                'unit'            => $array['unit'],
                'num'             => $array['num'],
                'text'             => $array['text'],
            ];
            $x++;
            $totalNum += $array['num'];
            $totalMoney += $array['money'];
        }
        $append = [
            'no'    => '合计',
            'num'   => $totalNum,
            'money' => $totalMoney
        ];
        $items[] = $append;
        $info['detail'] = $items;

        if ($isReturn) {
            return (new printTemplateClass())->start(self::page, $info);
        } else {
            return $info;
        }
    }
}
